package dao;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class BaseDBAO {
    Connection con;
    private boolean conFree = true;
    
    public static String url = "jdbc:mysql://localhost:3306/waimaiDB";
    public static String dbdriver = "com.mysql.jdbc.Driver";
    public static String username = "root";
    public static String password = "";
    
	public BaseDBAO() throws Exception {
		try {
//        	  Context initCtx = new InitialContext();
//            Context envCtx = (Context) initCtx.lookup("java:comp/env");
//            DataSource ds = (DataSource) envCtx.lookup("jdbc/waimaiDB");
//            con = ds.getConnection();
            
            Properties prop = new Properties();
            String propFile = "DB.properties";
            InputStream in = getClass().getClassLoader().getResourceAsStream(propFile);
            if(in != null) {
            	prop.load(in);
                url = prop.getProperty("url");
                dbdriver = prop.getProperty("dbdriver");
                username = prop.getProperty("username");
                password = prop.getProperty("password");
            } else {
            	throw new FileNotFoundException("property file '" + propFile + "'not found in classpath.");
            }
           
            Class.forName(dbdriver);
            con = DriverManager.getConnection(url, username, password);
            
            
        } catch (Exception ex) {
            System.out.println("Exception in AccountDBAO: " + ex);
            throw new Exception("Couldn't open connection to database: " + ex.getMessage());
        }
    }
    
    public void remove() {
        try {
            con.close();
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
    }
    
    protected synchronized Connection getConnection() {
        while (conFree == false) {
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }
        
        conFree = false;
        notify();
        
        return con;
    }
    
    protected synchronized void releaseConnection() {
        while (conFree == true) {
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }
        
        conFree = true;
        notify();
    }
}
